package weifei.wx.community.interceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;
import weifei.wx.community.service.WXService;

import java.io.PrintWriter;

public class UserTokenInterceptor implements HandlerInterceptor
{
    WXService wxService = new WXService();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception
    {
        var token = request.getHeader("access_token");
        if (token == null) {
            PrintWriter out = response.getWriter();
            out.println("没有权限");
            return false;
        }

//        Long uid = JWT.decode(token).getClaim("user_id").asLong();
//        String wxOpenid = JWT.decode(token).getClaim("wx_openid").asString();
//        if (uid == null || wxOpenid == null)
//        {
//            PrintWriter out = response.getWriter();
//            out.println("无效的token");
//            return false;
//        }

//        var user = User.create().select("wx_openid = ?", wxOpenid);
//        if (user == null)
//        {
//            PrintWriter out = response.getWriter();
//            out.println("不存在的用户");
//            return false;
//        }

//        try {
//            JWTVerifier jwtVerifier = JWT
//                    .require(Algorithm.HMAC256(wxOpenid + WXService.TOKEN_PASSWORD_AFTER))
//                    .build();
//            jwtVerifier.verify(token);
//        }
//        catch (JWTVerificationException e) {
//            PrintWriter out = response.getWriter();
//            out.println("token验证失败");
//            return false;
//        }

        if (!WXService.verifyUserAccessToken(token))
        {
            PrintWriter out = response.getWriter();
            out.println("token验证失败");
            return false;
        }


        return true;
    }
}


